package chances.epg.api.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RestController;

import chances.epg.api.controller.model.RestResponse;
import chances.epg.api.controller.model.ResultSetResponse;
import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.content.SearchContent;

@RestController
public class UserSearchController extends AbstractDataController {
	private static final Logger LOGGER = EpgLogFactory.getSystemLogger();

	public RestResponse searchList(ModelMap model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		int result = SUCCESS;

		// 查询参数
		Map<String, Object> params = new HashMap<String, Object>();

		try {
			String pageindex = request.getParameter("pageindex");
			String size = request.getParameter("Size");
			String title = request.getParameter("Title");
			if (StringUtils.isNotBlank(title)) {
				params.put("title", title);
			}

			String mainFolder = request.getParameter("Type");
			if (StringUtils.isNotBlank(mainFolder)) {
				params.put("mainFolder", mainFolder);
			}

			String tags = request.getParameter("Tag");
			if (StringUtils.isNotBlank(tags)) {
				params.put("tags", tags);
			}

			String region = request.getParameter("Region");
			if (StringUtils.isNotBlank(region)) {
				params.put("region", region);
			}

			String year = request.getParameter("Year");
			if (StringUtils.isNotBlank(year)) {
				params.put("year", year);
			}

			PageInfo pageInfo = null;
			if (StringUtils.isNotBlank(pageindex) && StringUtils.isNumeric(size)) {
				pageInfo = new PageInfo(Integer.valueOf(pageindex), Integer.valueOf(size));
			} else {
				pageInfo = new PageInfo(1, DEFAULT_SIZE);
			}

			List<SearchContent> searchlist = (List<SearchContent>) contentService.queryForList("searchContent", params,
					0, pageInfo.getPageBean());
			return new ResultSetResponse(result, searchlist, pageInfo.getPageBean());
		} catch (Throwable e) {
			LOGGER.error(e.getMessage(), e);
			return new RestResponse(ERROR);
		}
	}
}
